<script setup lang="ts">
import { ref, inject, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue'
import type { ModelType, FlowAPI } from '@/types/types';

const flowAPI = inject<FlowAPI>('flowAPI');
if (!flowAPI) {
    throw new Error('flowAPI 必须通过 provide 提供');
}

const isEditing = ref(false);
const currentEditIndex = ref<number | null>(null);

const models = ref<ModelType[]>([]);

const ModelOptions = ref<string[]>([])

const fetchModelNames = async () => {
    if (!flowAPI.getModelNames) {
        ElMessage.error('不支持获取服务端模型列表');
        return;
    }
    if (form.value.ApiUrl === '') {
        ElMessage.error('请先填写API地址');
        return;
    }
    try {
        const response = await flowAPI.getModelNames(form.value);
        if (response.code === 200 && Array.isArray(response.data)) {
            ModelOptions.value = response.data;
            form.value.ModelName = response.data[0];
        } else {
            ModelOptions.value = [];
            ElMessage.error(response.data.message);
            return;
        }
    } catch (err) {
        ElMessage.error('加载模型列表失败');
        return;
    }
}

const saveModel = () => {
    const newModel = { ...form.value };
    if (!flowAPI.addModel) {
        ElMessage.error('添加模型失败');
        return;
    }
    if (newModel.Name === "") {
        ElMessage.error('请填写模型名称');
        return;
    }
    if (newModel.ModelName === '') {
        ElMessage.error('请选择大语言模型');
        return;
    }
    if (newModel.ApiUrl === '') {
        ElMessage.error('请填写API地址');
        return;
    }
    flowAPI.addModel(newModel).then(() => {
        if (currentEditIndex.value !== null) {
            models.value[currentEditIndex.value] = newModel;
        } else {
            models.value.push(newModel);
        }
        ElMessage.success('添加模型成功');
    }).catch(() => {
        ElMessage.error('添加模型失败');
    });
};

const deleteModel = (index: number) => {
    if (!flowAPI.deleteModel) {
        ElMessage.error('删除模型失败');
        return;
    }
    flowAPI.deleteModel({
        "id": models.value[index].ID
    }).then(() => {
        ElMessage.success('删除模型成功');
        models.value.splice(index, 1);
    }).catch(() => {
        ElMessage.error('删除模型失败');
    });
};

const editModel = (index: number) => {
    form.value = { ...models.value[index] };
    isEditing.value = true;
    currentEditIndex.value = index;
};

// 获取模型列表
const loadModels = async () => {
    try {
        if (!flowAPI.getModelList) {
            ElMessage.error('获取模型列表失败');
            return;
        }
        const res = await flowAPI.getModelList();
        if (res.code !== 200) {
            ElMessage.error('获取模型列表失败');
            return;
        }
        if (Array.isArray(res.data)) {
            models.value = res.data;
        } else {
            models.value = [];
        }
    } catch (err) {
        ElMessage.error('加载模型列表失败');
    }
};

onMounted(() => {
    loadModels();
});

const resetForm = () => {
    form.value = {
        ID: 0,
        Name: '',
        ModelName: '',
        ModelType: 'ollama',
        ApiKey: '',
        ApiUrl: '',
        MaxContextLength: 4096,
        StreamingEnabled: true
    };
};

const form = ref<ModelType>({
    ID: 0,
    Name: '',
    ModelType: 'ollama',
    ModelName: 'Qwen',
    ApiKey: '',
    ApiUrl: 'http://localhost:11434',
    MaxContextLength: 4096,
    StreamingEnabled: true
});

</script>

<template>
    <div class="large-model-settings">
        <el-row :gutter="20">
            <el-col :span="24">
                <el-card class="box-card" shadow="never">
                    <template #header>
                        <div class="card-header">
                            <h3>模型列表</h3>
                        </div>
                    </template>
                    <div class="table-wrapper">
                        <el-table :data="models" style="width: 100%; table-layout: fixed;">
                            <el-table-column prop="Name" label="模型名"></el-table-column>
                            <el-table-column prop="ModelName" label="大模型"></el-table-column>
                            <el-table-column prop="ApiUrl" label="API 地址"></el-table-column>
                            <el-table-column label="流式输出" width="80px">
                                <template #default="{ row }">
                                    <el-tag :type="row.streamingEnabled ? 'success' : 'info'">
                                        {{ row.streamingEnabled ? '启用' : '未启用' }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="140px">
                                <template #default="{ $index }">
                                    <el-button size="small" @click="editModel($index)">编辑</el-button>
                                    <el-button size="small" type="danger" @click="deleteModel($index)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-card>
            </el-col>

            <el-col :span="24">
                <el-card class="box-card" shadow="never">
                    <template #header>
                        <div class="card-header">
                            <h3>模型配置</h3>
                            <div style="display: flex; gap: 10px;">
                                <el-button type="success" size="small" @click="resetForm()">新建</el-button>
                                <el-button type="primary" size="small" @click="saveModel">保存</el-button>
                            </div>
                        </div>
                    </template>
                    <el-form :model="form" label-width="140px" @submit.prevent="saveModel">
                        <!-- 表单项 -->

                        <!-- 模型名称 -->
                        <el-form-item label="模型名称">
                            <el-input v-model="form.Name" placeholder="自定义名称" />
                        </el-form-item>

                        <el-form-item label="模型类型">
                            <el-select v-model="form.ModelType" placeholder="请选择模型类型" style="width: 100%">
                                <el-option label="OpenAI" value="openai" />
                                <el-option label="Ollama" value="ollama" />
                            </el-select>
                        </el-form-item>

                        <!-- API 地址 -->
                        <el-form-item label="API 地址">
                            <el-input v-model="form.ApiUrl" placeholder="例如：http://localhost:11434" />
                        </el-form-item>

                        <!-- API Key -->
                        <el-form-item label="API Key">
                            <el-input v-model="form.ApiKey" type="password" show-password placeholder="请输入API密钥" />
                        </el-form-item>

                        <el-form-item label="操作">
                            <el-button type="warning" @click="fetchModelNames" :disabled="form.apiUrl === ''">
                                <Refresh style="width: 1em; height: 1em" />
                                获取模型列表
                            </el-button>
                            <div v-if="form.ApiUrl === ''" style="color: #999; font-size: 12px;">
                                请先填写 API 地址，再点击【获取模型列表】
                            </div>
                        </el-form-item>

                        <el-form-item label="大语言模型">
                            <el-select v-model="form.ModelName" placeholder="请选择模型名称" style="width: 100%" filterable
                                clearable popper-class="custom-select-dropdown">
                                <el-option v-for="name in ModelOptions" :key="name" :label="name" :value="name" />
                            </el-select>
                        </el-form-item>

                        <!-- 最大上下文长度 -->
                        <el-form-item label="最大上下文长度">
                            <el-input-number v-model="form.MaxContextLength" :min="64" :max="32768" />
                        </el-form-item>

                        <!-- 是否启用流式输出 -->
                        <el-form-item label="启用流式输出">
                            <el-switch v-model="form.StreamingEnabled" />
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    font-weight: bold;
    color: #333;
}

.large-model-settings {
    padding: 20px;
    background-color: #f9f9f9;
}

.box-card {
    border-radius: 8px;
}

.table-wrapper {
    width: 70vw;
    height: 50vh;
    overflow: auto;
    position: relative;
}

.table-wrapper::-webkit-scrollbar {
    height: 12px;
}

/* 固定宽度滚动条占位 */
.table-wrapper::after {
    content: '';
    display: block;
    height: 12px;
    width: 100%;
    visibility: hidden;
    flex-shrink: 0;
}

.id-wrapper {
    /* 填充剩余空间 */
    flex: 1 1 auto;
    min-width: 400px;
    display: inline-block;
}

.id-text {
    width: 100%;
    padding: 6px 12px;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    font-family: monospace;
    font-size: 13px;
    color: #666;
    box-sizing: border-box;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.custom-select-dropdown .el-select-dropdown__item {
    height: auto;
    white-space: normal;
    line-height: 1.5;
}

.custom-select-dropdown .el-select-dropdown {
    max-height: 400px;
    overflow: auto;
}
</style>